import 'package:flutter/material.dart';
import '../../../../domain/services/directory_service.dart';
import '../../../../data/api/directories_api.dart';
import 'file_item.dart';
import 'filter_tabs.dart';

/// 过滤后的文件视图组件
class FilteredFilesView extends StatelessWidget {
  /// 目录服务
  final DirectoryService directoryService;

  /// 当前筛选的标签索引
  final int filterIndex;

  /// 文件点击回调
  final Function(FileItem)? onFileTap;

  /// 文件菜单操作回调
  final Function(String, FileItem)? onFileMenuAction;

  const FilteredFilesView({
    Key? key,
    required this.directoryService,
    required this.filterIndex,
    this.onFileTap,
    this.onFileMenuAction,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 根据当前选中的标签筛选文件
    final String fileType = FilterTabs.getSelectedFileType(filterIndex);
    final filteredFiles =
        directoryService.files
            .where((file) => file.fileType == fileType)
            .toList();

    // 如果没有匹配的文件，显示空状态
    if (filteredFiles.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              filterIndex == 1
                  ? Icons.image_not_supported
                  : filterIndex == 2
                  ? Icons.videocam_off
                  : Icons.description,
              size: 64,
              color: Colors.grey,
            ),
            const SizedBox(height: 16),
            Text(
              '没有找到${filterIndex == 1
                  ? "图片"
                  : filterIndex == 2
                  ? "视频"
                  : "文档"}',
              style: const TextStyle(color: Colors.grey),
            ),
          ],
        ),
      );
    }

    // 显示筛选后的文件列表
    return RefreshIndicator(
      onRefresh:
          () => directoryService.navigateToDirectory(
            directoryService.currentDirectoryId,
          ),
      child: ListView.builder(
        padding: const EdgeInsets.all(0),
        itemCount: filteredFiles.length,
        itemBuilder:
            (context, index) => FileItemWidget(
              file: filteredFiles[index],
              onTap: () => _handleFileTap(context, filteredFiles[index]),
              onMenuAction:
                  (action, file) =>
                      _handleFileMenuAction(context, action, file),
            ),
      ),
    );
  }

  /// 处理文件点击事件
  void _handleFileTap(BuildContext context, FileItem file) {
    if (onFileTap != null) {
      onFileTap!(file);
    } else {
      // 默认行为：显示预览即将推出提示
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('预览 ${file.fileName} 功能即将推出')));
    }
  }

  /// 处理文件菜单操作
  void _handleFileMenuAction(
    BuildContext context,
    String action,
    FileItem file,
  ) {
    if (onFileMenuAction != null) {
      onFileMenuAction!(action, file);
    } else {
      // 默认行为
      switch (action) {
        case 'delete':
          _showDeleteConfirmDialog(
            context,
            '删除文件',
            '确定要删除文件 "${file.fileName}" 吗？',
            () => directoryService.deleteFile(file.id),
          );
          break;
        case 'download':
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('下载文件功能即将推出')));
          break;
        case 'share':
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('分享文件功能即将推出')));
          break;
        case 'rename':
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('文件重命名功能即将推出')));
          break;
      }
    }
  }

  /// 显示删除确认对话框
  void _showDeleteConfirmDialog(
    BuildContext context,
    String title,
    String content,
    Function() onConfirm,
  ) {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: Text(title),
            content: Text(content),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('取消'),
              ),
              ElevatedButton(
                onPressed: () {
                  Navigator.of(context).pop();
                  onConfirm();
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.red.withOpacity(0.1),
                  foregroundColor: Colors.red,
                ),
                child: const Text('删除'),
              ),
            ],
          ),
    );
  }
}
